/*本模块功能:用户管理(管理员)
        editor:yxj
        20180508
        */
$(function() {

    var th = '<tr>' +
        '<th class="col-lg-2"><input type="checkbox" name="controlAll" id="controlAll" class="allCheck"></th>' +
        '<th class="col-lg-6">姓名</th>' +
        '<th class="col-lg-4">性别</th>' +
        '<th class="col-lg-5">工号</th>' +
        '<th class="col-lg-5">联系方式</th>' +
        '<th class="col-lg-5">部门</th>' +
        '<th class="col-lg-5">角色</th>' +
        '<th class="col-lg-6">操作</th>' +
        '</tr>';
    /*列表头*/
    var confirm1 = new  Confirm;
    var Alert1 = new  Alert;
    var $mb = $(".mb");
    function myMessage(message) { //添加用户

        var departmentStr = '<option value="1">请选择</option>';
        var roleStr = '<option value="1">请选择</option>';
        for(key in message.depList) {
            departmentStr += '<option value="1" depId="' + message.depList[key].depId + '">' + message.depList[key].depName + '</option>';
        }
        for(key in message.roleList) {
            roleStr += '<option value="1" roleId="' + message.roleList[key].roleId + '">' + message.roleList[key].roleName + '</option>';
        }

        return'<div style="display:block;height: 350px;" class=\"popup addChapterBox\">' +
            '<div class=\"popup_box\">' +
            '<div class=\"popup_contenthead\">添加用户<img class=\"popup_img\" src=\"pc/images/ico_alertDel.png\"></div>' +
            '<div style="padding: 20px 30px 0 30px;"><div>' +
            '<div class="fl inputRight"><label for="Name">姓&ensp;&ensp;&ensp;&ensp;名:&ensp;</label><input type="text" id="name" class="publicText" placeholder="请输入姓名"/></div>' +
            '<div class="fr sex"><span style="margin-right:0;">性&ensp;&ensp;&ensp;&ensp;别:&ensp;</span>' +
            '<input type="radio" checked="checked" name="sex" id="man" value="" /><label for="man" class="checked">男</label>' +
            '<input type="radio" name="sex" id="woman" value="" /><label for="woman">女</label>' +
            '</div>' +
            '<div class="fl inputRight"><label for="departName">联系方式:&ensp;</label><input type="text" id="phone" class="publicText" placeholder="请输入联系方式"/></div>' +
            '<div class="fr inputRight"><label for="departName">工&ensp;&ensp;&ensp;&ensp;号:&ensp;</label><input placeholder="请输入工号" type="text" id="workNum" class="publicText" /></div>' +

            '<div class="fl inputRight"><label for="departNames">部&ensp;&ensp;&ensp;&ensp;门:&ensp;</label>' +
            '<select id="department" class="publicSelect">' +
            departmentStr +
            '</select>' +
            '</div>' +

            '<div class="fr inputRight"><label for="departNames">角&ensp;&ensp;&ensp;&ensp;色:&ensp;</label>' +
            '<select id="role" class="publicSelect">' +
            roleStr +
            '</select>' +
            '</div>' +
            '<div class="fl inputRight"><label for="pass">密&ensp;&ensp;&ensp;&ensp;码:&ensp;</label><input type="text" id="pass" class="publicText" placeholder="请输入密码"/></div>' +
            '<div class="fr inputRight"><label for="repass">确认密码:&ensp;</label><input type="text" id="repass" class="publicText" placeholder="请再次输入密码"/></div>' +
            '</div>' +
            '<div class="clear"></div>' +
            '<div class=\"popup_btn\">' +
            '<a  class=\"popup_confirm exportBtn hover-btn publicBtn\">确定</a>' +
            '<a class=\"popup_close exportCancle\">取消</a>' +
            '</div>' +
            '<div class="clear"></div>' +
            '</div>';
    }

    function setUser(mes,sexThis) { //编辑用户

        var departmentStr = '<option value="0">请选择</option>';
        var roleStr = '<option value="0">请选择</option>';
        for(key in mes.depList) {
            departmentStr += '<option value="1" depId="' + mes.depList[key].depId + '">' + mes.depList[key].depName + '</option>';
        }
        for(key in mes.roleList) {
            roleStr += '<option value="1" roleId="' + mes.roleList[key].roleId + '">' + mes.roleList[key].roleName + '</option>';
        }
        if(sexThis == "男") {
            var sexList = '<input type="radio" checked="checked" name="sex" id="man" value=""/><label for="man" class="checked">男</label> <input type="radio" name="sex" id="woman" value=""/><label for="woman">女</label>';
        }
        if(sexThis == "女") {
            var sexList = '<input type="radio"  name="sex" id="man" value=""/><label for="man" >男</label> <input type="radio" checked="checked"  name="sex" id="woman" value=""/><label for="woman" class="checked">女</label>';
        }
        return '<div style="display: block;" class=\"popup editChapterBox\">' +
            '<div class=\"popup_box\">' +
            '<div class=\"popup_contenthead\">修改用户<img class=\"popup_img\" src=\"pc/images/ico_alertDel.png\"></div>' +
            '<div  style="padding: 20px 30px 0 30px;"><div >' +
            '<div class="fl inputRight"><label for="departName" class="fl">姓&ensp;&ensp;&ensp;&ensp;名:&ensp;</label><div class="fl" title="' + mes.user.userName + '">' + mes.user.userName + '</div></div>' +
            '<div class="fr sex"><span>性&ensp;&ensp;&ensp;&ensp;别:&ensp;</span>' +
            sexList+
            '</div>' +
            '<div class="fl inputRight"><label for="departName">联系方式:&ensp;</label><input type="text" id="phone" class="publicText"  placeholder="请输入联系方式" value="' + mes.user.telephoneNum + '"/></div>' +
            '<div class="fr inputRight"><label for="departName"  class="fl">工&ensp;&ensp;&ensp;&ensp;号:&ensp;</label><div class="fl" id="workId" title="' + mes.user.stuorteaId + '">' + mes.user.stuorteaId + '</div></div>' +
            '<div class="fl inputRight"><label for="departNames">部&ensp;&ensp;&ensp;&ensp;门:&ensp;</label>' +
            '<select id="department" class="publicSelect">' +
            departmentStr +
            '</select>' +
            '</div>' +
            '<div class="fr inputRight"><label for="departNames">角&ensp;&ensp;&ensp;&ensp;色:&ensp;</label>' +
            '<select id="role" class="publicSelect">' +
            roleStr +
            '</select>' +
            '</div>' +
            '</div>' +
            '<div class="clear"></div><div class=\"popup_btn\">' +
            '<a  class=\"popup_confirm exportBtn hover-btn publicBtn\">确定</a>' +
            '<a class=\"popup_close exportCancle \">取消</a>' +
            '</div>' +
            '</div>';
    }

    function tabelModel(opt) {/*列表内容*/
        var sex = "";
        var str='<a  stuorteaId="' + opt.stuorteaId + '" href="javascript:;" class="set">修改</a>';
        var inp='<input value="0" name="selecteds" type="checkbox" class="oneCheck" stuorteaId="' + opt.stuorteaId + '"/>';
        if(opt.roleId==3){
            str="";
            inp="<div class='falseInput'></div>";
        }
        return '<tr data-num="0">' +
            '<td class="col-lg-2">'+inp+'</td>' +
            '<td class="col-lg-5" title="' + opt.userName + '">' + opt.userName + '</td>' +
            '<td class="col-lg-2 sexName">' + opt.sexName + '</td>' +
            '<td class="col-lg-6"  title="' + opt.stuorteaId + '">' + opt.stuorteaId + '</td>' +
            '<td class="col-lg-3"  title="' + opt.telephoneNum + '">' + opt.telephoneNum + '</td>' +
            '<td class="col-lg-3"  title="' + opt.depName + '">' + opt.depName + '</td>' +
            '<td class="col-lg-3"  title="' + opt.roleName + '">' + opt.roleName + '</td>' +
            '<td class="col-lg-4">' +
            str +
            '<a class="initialization" href="javascript:;"  stuorteaId="' + opt.stuorteaId + '">初始化密码</a>' +
            '</td>' +
            '</tr>';

    }
    var loading1 = new Loading();//监控全局ajax添加loading
    loading1.init();
    var $departNames = $("#departNames");
    var $tableBox = $(".tableBox");
    var $searchBtn = $(".searchBtn");
    var index = {
        some:'',
        init: function () {
            this.bind();
        },
        bind: function () {
            var self = this;
            var json = {
                "pageNow": 1,
                "pageSize": 10,
                "roleMark":3,
                "roleId":3,
                "selecetRoleId":3
            };
            self.some = json;
            this.tableList(json);
            var self = this;
            $(".deleteUser").off("click").on("click", function() {
                self.delListEvent();
            });
            $(".addUser").off("click").on("click", function() {
                self.addUser();
            });
            $searchBtn.off("click").on("click", function() {
                var depId = $departNames.val();
                var keyWord = $("#keyWord").val();
                var jsonStr = {
                    "pageNow": 1,
                    "pageSize": 10,
                    "roleMark":3,
                    "roleId":3,
                    "selecetRoleId":3
                };
                if(depId != 0) {
                    jsonStr.depId = depId;
                }
                if(keyWord != '') {
                    jsonStr.userName = keyWord;
                }
                self.tableList(jsonStr);
                self.some = jsonStr;
            });
        },
        editUser:function () {
            var self = this;
            $(".set").off("click").click(function() { //修改信息
                var stuorteaId = $(this).parents("tr").children("td").children(".oneCheck").attr("stuorteaId");
                var par = {
                    "stuorteaId": stuorteaId
                };

                var sexThis = $(this).parents("tr").children(".sexName").html();//性别

                $.ajax({
                    type: "post",
                    url: "skipSaveMember",
                    async: true,
                    data: {
                        "jsonStr": JSON.stringify(par)
                    },

                    success: function (msg) {

                        var msgNew = JSON.parse(msg);

                        var str = setUser(msgNew, sexThis);
                        $("body").append(str);
                        $mb.show();
                        $(".exportCancle").off("click").click(function () {
                            $(".editChapterBox").remove();
                            $mb.hide();
                        });
                        $(".popup_img").off("click").click(function () {
                            $(".editChapterBox").remove();
                            $mb.hide();
                        });
                        $("#department option").each(function(){//加载部门
                            if($(this).attr("depid")==msgNew.user.depId){
                                $(this).attr("selected","selected");
                            }
                        });
                        $("#role option").each(function(){//加载角色
                            if($(this).attr("roleId")==msgNew.user.roleId){
                                $(this).attr("selected","selected");
                            }
                        });
                        $(".sex input" ).off("click").click(function() {

                            $(this).next("label").addClass("checked").siblings("label").removeClass("checked");
                        });
                        $(".exportBtn").off("click").click(function () {
                            var stuorteaId = $("#workId" ).html();
                            /*var userName = $("#name" ).val();*/
                            var telephoneNum = $("#phone" ).val();
                            var depId = $("#department option:selected" ).attr("depid");
                            var roleId = $("#role option:selected" ).attr("roleid");
                            var n = /^[1-9]\d*$|^0$/;
                             if(stuorteaId.length == 0) {
                                Alert1.content = "请输入工号";
                                Alert1.init();
                                Alert1.show();
                                return false;
                            } else  if(verification.stuorTeaIdcode(stuorteaId) !== true) {
                                Alert1.content = "请输入1-15位数字或英文的工号/学号";
                                Alert1.init();
                                Alert1.show();
                                return false;
                            }else  if(depId==null) {
                                Alert1.content = "请选择部门";
                                Alert1.init();
                                Alert1.show();
                                return false;
                            } else if(roleId==null) {
                                Alert1.content = "请选择角色";
                                Alert1.init();
                                Alert1.show();
                                return false;
                            }  else {

                                if ($(".sex .checked").html() == "男") {
                                    var userSex = 'm';
                                } else {
                                    var userSex = 'f';
                                }
                                var parameter = {

                                    "telephoneNum": telephoneNum,
                                    "userSex": userSex,
                                    "stuorteaId": stuorteaId,
                                    "depId": parseInt(depId),
                                    "roleId": parseInt(roleId)

                                };

                                $.ajax({
                                    type: "post",
                                    url: "saveMember",
                                    async: true,
                                    data: {
                                        "jsonStr": JSON.stringify(parameter)
                                    },

                                    success: function (msg) {

                                        var msgNew = JSON.parse(msg);

                                        if(msgNew.result == "success") {
                                            Alert1.content = "保存成功";
                                            Alert1.success = function () {
                                                var json = JSON.stringify({
                                                    "pageName":"adminUserManagement"
                                                });
                                                window.location.href = "skipPage?jsonStr="+json;
                                            };
                                            Alert1.init();
                                            Alert1.show();
                                        } else {
                                            if(msgNew.errorMsg != "" && msgNew.errorMsg != undefined){
                                                Alert1.content = msgNew.errorMsg;
                                            }else{
                                                Alert1.content = "保存失败";
                                            }
                                            Alert1.init();
                                            Alert1.show();

                                        }

                                    },
                                    error: function (data, status, xhr) {
                                        var json = JSON.stringify({
                                            "pageName": "error"
                                        });
                                        window.location.href = "skipPage?jsonStr=" + json;

                                    }
                                });
                            }
                        });
                    }
                });
            });
        },
        addUser:function () {
            var par = {
                "pageType": 2
            };

            $.ajax({
                type: "post",
                url: "skipAddMember",
                async: true,
                data: {
                    "jsonStr": JSON.stringify(par)
                },

                success: function(msg) {

                    var msgNew = JSON.parse(msg);

                    var str = myMessage(msgNew);
                    $("body").append(str);
                    $mb.show();
                    $(".exportCancle").off("click").click(function () {
                        $(".addChapterBox").remove();
                        $mb.hide();
                    });
                    $(".popup_img").off("click").click(function () {
                        $(".addChapterBox").remove();
                        $mb.hide();
                    });
                    $(".sex input" ).off("click").click(function() {

                        $(this).next("label").addClass("checked").siblings("label").removeClass("checked");
                    });
                    $(".exportBtn").off("click").click(function () {
                        var stuorteaId = $("#workNum" ).val();
                        var userName = $("#name" ).val();
                        var telephoneNum = $("#phone" ).val();
                        var depId = $("#department option:selected" ).attr("depid");
                        var roleId = $("#role option:selected" ).attr("roleid");
                        var n = /^[1-9]\d*$|^0$/;
                        if(userName==""){
                            Alert1.content = "请输入姓名";
                            Alert1.init();
                            Alert1.show();
                            return false;
                        }else if(verification.specialCode(userName) !== true) {
                            Alert1.content = "不能输入特殊字符";
                            Alert1.init();
                            Alert1.show();
                            return false;
                        } else if(stuorteaId.length == 0) {
                            Alert1.content = "请输入工号";
                            Alert1.init();
                            Alert1.show();
                            return false;
                        } else  if(verification.stuorTeaIdcode(stuorteaId) !== true) {
                            Alert1.content = "请输入1-15位数字或英文的工号/学号";
                            Alert1.init();
                            Alert1.show();
                            return false;
                        }else  if(depId==null) {
                            Alert1.content = "请选择部门";
                            Alert1.init();
                            Alert1.show();
                            return false;
                        } else if(roleId==null) {
                            Alert1.content = "请选择角色";
                            Alert1.init();
                            Alert1.show();
                            return false;
                        } else if($("#pass").val()=='') {
                            Alert1.content = "请输入密码";
                            Alert1.init();
                            Alert1.show();
                            return false;
                        } else if($("#repass").val()=='') {
                            Alert1.content = "请再次输入密码";
                            Alert1.init();
                            Alert1.show();
                            return false;
                        } else if($("#repass").val()!=$("#pass").val()) {
                            Alert1.content = "两次密码不一致，请重新输入";
                            Alert1.init();
                            Alert1.show();
                            return false;
                        }  else {

                            if($(".sex .checked" ).html() == "男") {
                                var userSex = 'm';
                            } else {
                                var userSex = 'f';
                            }
                            var parameter = {
                                "telephoneNum": telephoneNum,
                                "userName": userName,
                                "userSex": userSex,
                                "stuorteaId": stuorteaId,
                                "depId": depId,
                                "roleId": roleId,
                                "classId":0,
                                "headIcon":"",
                                "imageUrl":"",
                                "departmentId":0,
                                "professionId":0,
                                "userContect":"",
                                "password":$("#pass").val()
                            };

                            $.ajax({
                                type: "post",
                                url: "addMember",
                                async: true,
                                data: {
                                    "jsonStr": JSON.stringify(parameter)
                                },

                                success: function(msg) {

                                    var msgNew = JSON.parse(msg);
                                    if(msgNew.result == "success") {
                                        Alert1.content = "添加成功";
                                        Alert1.success = function () {
                                            var json = JSON.stringify({
                                                "pageName":"adminUserManagement"
                                            });
                                            window.location.href = "skipPage?jsonStr="+json;
                                        };
                                        Alert1.init();
                                        Alert1.show();
                                    } else {
                                        if(msgNew.errorMsg != "" && msgNew.errorMsg != undefined){
                                            Alert1.content = msgNew.errorMsg;
                                        }else{
                                            Alert1.content = "添加失败";
                                        }
                                        Alert1.init();
                                        Alert1.show();

                                    }

                                },
                                error: function(data, status, xhr) {
                                    var json = JSON.stringify({
                                        "pageName": "error"
                                    });
                                    window.location.href = "skipPage?jsonStr=" + json;

                                }
                            });
                        }
                    });
                    // var sub = function() {

                    // };



                },
                error: function(data, status, xhr) {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;

                }
            });
        },
        resetPass:function () {
            $(".initialization").off("click").click(function() { //重置密码
                var stuorteaId = $(this).attr("stuorteaId");
                var parameter = {
                    "stuorteaId": stuorteaId
                };

                $.ajax({
                    type: "post",
                    url: "resetPwd",
                    async: true,
                    data: {
                        "jsonStr": JSON.stringify(parameter)
                    },

                    success: function(msg) {

                        var msgNew = JSON.parse(msg);

                        if(msgNew.result == "success") {
                            Alert1.content = "初始化密码成功";
                            Alert1.init();
                            Alert1.show()

                        } else {
                            if(msg.errorMsg != "" && msg.errorMsg != undefined){
                                Alert1.content = msg.errorMsg;
                            }else{
                                Alert1.content = "初始化密码失败";
                            }
                            Alert1.init();
                            Alert1.show()

                        }

                    },
                    error: function(data, status, xhr) {
                        var json = JSON.stringify({
                            "pageName": "error"
                        });
                        window.location.href = "skipPage?jsonStr=" + json;

                    }
                });

            });
        },
        tableList:function (jsons) {
            var self = this;
            var json = JSON.stringify(jsons);
            loading1.show();
            $.ajax({
                type: "post",
                url: "getMemberList",
                data: {
                    "jsonStr": json
                },
                async: true,
                success: function(msg) {
                    loading1.hide();
                    msg = JSON.parse(msg);
                    $tableBox.empty();
                    if(msg.result == "success"){
                        if(msg.memberList.length != 0) {
                            //列表
                            var tabel = "";
                            $.map(msg.memberList, function(opt) {
                                tabel += tabelModel(opt);
                            });
                            $tableBox.append(th + tabel);
                            self.allCheckEvent();
                            self.resetPass();
                            self.editUser();
                        } else {
                            var trImg = "<tr><td colspan='8'><img style='position:relative;margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无数据</p></td></tr>";
                            $tableBox.append(th + trImg)
                        }
                        var sumpage = msg.totalPage;
                        if(sumpage == 0){
                            sumpage = 1;
                        }
                        var nowpage = 1;
                        var pagenumber = 10;
                        $(".tcdPageCode").createPage({
                            pageCount: sumpage, //总页数
                            current: nowpage, //当前页数
                            pageNumber: pagenumber, //每页显示数量
                            backFn: function(p) {
                                nowpage = p;
                                if(nowpage >= sumpage) {
                                    nowpage = sumpage;
                                }
                                var jsonStr = jsons;
                                jsonStr.pageNow = nowpage;
                                loading1.show();
                                $.ajax({
                                    type: "post",
                                    url: "getMemberList",
                                    data: {
                                        "jsonStr": JSON.stringify(jsonStr)
                                    },
                                    async: true,
                                    success: function(msg) {
                                        loading1.hide();
                                        msg = JSON.parse(msg);

                                        //列表
                                        $tableBox.empty();
                                        var tabel = "";
                                        $.map(msg.memberList, function(opt) {
                                            tabel += tabelModel(opt);
                                        });
                                        $tableBox.append(th + tabel);
                                        self.allCheckEvent();
                                        self.resetPass();
                                        self.editUser();
                                        //获取院系
                                        $departNames.html("<option value=\"0\">请选择</option>");
                                        $.map(msg.depAllList, function(opt) {
                                            $departNames.append("<option value=" + opt.depId + ">" + opt.depName + "</option>");
                                        });
                                        if(msg.SearObjectMap!=null){
                                            if(msg.SearObjectMap.depId!=undefined){
                                                $departNames.val(msg.SearObjectMap.depId);
                                            }
                                            if(msg.SearObjectMap.userName!=undefined){
                                                $("#keyWord").val(msg.SearObjectMap.userName);
                                            }
                                        }
                                    }
                                });
                            }
                        });
                        //获取院系
                        $departNames.html("<option value=\"0\">请选择</option>");
                        $.map(msg.depAllList, function(opt) {
                            $departNames.append("<option value=" + opt.depId + ">" + opt.depName + "</option>");
                        });
                        if(msg.SearObjectMap!=null){
                            if(msg.SearObjectMap.depId!=undefined){
                                $departNames.val(msg.SearObjectMap.depId);
                            }
                            if(msg.SearObjectMap.userName!=undefined){
                                $("#keyWord").val(msg.SearObjectMap.userName);
                            }
                        }

                    }else{
                        if(msg.failMsg != undefined){
                            if(msg.failMsg == "暂无权限"){
                                parent.location.reload(true);
                            }else{
                                Alert1.content = msg.failMsg;
                                Alert1.init();
                                Alert1.show();
                            }
                        }else{
                            if (msg.errorMsg != "" && msg.errorMsg != undefined) {
                                Alert1.content = msg.errorMsg;
                            } else {
                                Alert1.content = "获取失败";
                            }
                            Alert1.init();
                            Alert1.show();
                        }
                    }


                },
                error:function () {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;
                }
            });
        },
        delListEvent: function() { //批量删除
            var self = this;
            if($(".oneCheck[value=1]").length == 0) {

                Alert1.content = "请选择要删除的用户";
                Alert1.init();
                Alert1.show();
            } else {
                confirm1.content = "确认删除选中的用户吗？";
                confirm1.success = function() {
                    var list = [];
                    for(var i = 0; i < $(".oneCheck[value=1]").length; i++) {
                        list.push($(".oneCheck[value=1]").eq(i).attr("stuorteaId"));
                    }

                    var deleteDepartmentparameters = {
                        "list": list,
                        "marks":2
                    };

                    $.ajax({
                        type: "post",
                        url: "delMembers",
                        async: true,
                        data: {
                            "jsonStr": JSON.stringify(deleteDepartmentparameters),
                            "memType":0
                        },

                        success: function(msg) {

                            var msgNew = JSON.parse(msg);

                            if(msgNew.result == "success") {
                                Alert1.content = "删除成功";
                                Alert1.success = function () {
                                    self.tableList(self.some);
                                };
                                Alert1.init();
                                Alert1.show();
                            } else {
                                if(msg.errorMsg != "" && msg.errorMsg != undefined){
                                    Alert1.content = msg.errorMsg;
                                }else{
                                    Alert1.content = "删除失败";
                                }
                                Alert1.init();
                                Alert1.show();

                            }

                        },
                        error: function(data, status, xhr) {
                            var json = JSON.stringify({
                                "pageName": "error"
                            });
                            window.location.href = "skipPage?jsonStr=" + json;

                        }
                    });
                };
                confirm1.init();
                confirm1.show();

            }
        },
        allCheckEvent: function() {
            //全选
            allCheck.init("controlAll", "oneCheck");
        }
    };
    index.init();

});